package com.tim.app.ui.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.application.library.net.StringResponseCallback;
import com.application.library.util.ClickUtil;
import com.google.gson.Gson;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.cache.CacheMode;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.tim.app.R;
import com.tim.app.RT;
import com.tim.app.constant.AppKey;
import com.tim.app.server.api.API_App;
import com.tim.app.server.api.API_Discover;
import com.tim.app.server.api.API_Found;
import com.tim.app.server.api.API_Statistics;
import com.tim.app.server.entry.Advertisement;
import com.tim.app.server.logic.UserManager;
import com.tim.app.server.net.ServerAddressManager;
import com.tim.app.server.result.AdvertisementListResult;
import com.tim.app.server.result.FoundCacheUpdateResult;
import com.tim.app.server.result.InitResult;
import com.tim.app.server.result.ResponseResult;
import com.tim.app.ui.activity.setting.PhoneLoginActivity;
import com.tim.app.ui.dialog.UpdateDialog;
import com.tim.app.util.BitmapLoader;
import com.tim.app.util.FileSizeUtil;
import com.tim.app.util.PhoneInfoUtil;
import com.tim.app.util.PreferenceHelper;
import com.tim.app.util.ViewGT;

public class SplashActivity extends BaseActivity {
    private static final String TAG = "SplashActivity";
    private static final String preference_key = "SplashActivity";

    private static final String preference_first_key = "isFirst";

    private static final int MESSAGE_WHAT_GOTO_MAINACTIVITY = 0X01;
    private static final int MESSAGE_WHAT_GOTO_GUIDEACTIVITY = 0X02;

    private static int DELAY_TIME = 500;

    private ImageView iv_splash;
    private TextView tvSkipAd;
    private boolean isFrist = false;

    private Advertisement advert;
    private int OVERLAY_PERMISSION_REQ_CODE = 1000;


    @Override
    protected void onBeforeSetContentLayout() {
        super.onBeforeSetContentLayout();
        getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    @Override
    protected int getLayoutId() {

        return R.layout.activity_splash;
    }

    @Override
    public void initView() {
        iv_splash = (ImageView) findViewById(R.id.iv_splash);
        tvSkipAd = (TextView) findViewById(R.id.tvSkipAd);
        iv_splash.setOnClickListener(this);
        tvSkipAd.setOnClickListener(this);
    }

    private boolean isInit = false;
    AlertDialog alertDialog = null;

    private boolean isPauseForPermission = false;

    @Override
    public void initData() {
        //用版本号 做闪屏引导显示的记录  如果版本变了 就再显示一次闪屏的多图引导
        String version = PreferenceHelper.ins().getStringShareData(preference_key, "");
        isInit = PreferenceHelper.ins().getBooleanShareData(preference_first_key, false);
        if (PhoneInfoUtil.getAppVersionName(this).equals(version)) {
            isFrist = false;
        } else {
            isFrist = true;
            PreferenceHelper.ins().storeShareStringData(preference_key, PhoneInfoUtil.getAppVersionName(this));
            PreferenceHelper.ins().commit();
        }


        if (Build.VERSION.SDK_INT >= 23) {
            if (Settings.canDrawOverlays(this)) {
//                //有悬浮窗权限开启服务绑定 绑定权限
                UserManager.ins().loadUserInfo(new UserManager.LoadCallBack() {
                    @Override
                    public void onComlpete() {
                        if (UserManager.ins().isLogin()) {
                            UserManager.ins().loginChat(UserManager.ins().getUserId());
                        }
                        initServerInfo();
                    }
                });
            } else {
                AlertDialog.Builder builder = new AlertDialog.Builder(SplashActivity.this);
                builder.setMessage("打开悬浮框权限");
                builder.setPositiveButton("前往", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        isPauseForPermission = true;
                        Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
                        startActivityForResult(intent, OVERLAY_PERMISSION_REQ_CODE);
                        alertDialog.dismiss();
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        alertDialog.dismiss();
                        UserManager.ins().loadUserInfo(new UserManager.LoadCallBack() {
                            @Override
                            public void onComlpete() {
                                if (UserManager.ins().isLogin()) {
                                    UserManager.ins().loginChat(UserManager.ins().getUserId());
                                }
                                initServerInfo();
                            }
                        });
                    }
                });
                builder.setCancelable(false);
                alertDialog = builder.create();
                alertDialog.show();

            }
        } else {
            UserManager.ins().loadUserInfo(new UserManager.LoadCallBack() {
                @Override
                public void onComlpete() {
                    if (UserManager.ins().isLogin()) {
                        UserManager.ins().loginChat(UserManager.ins().getUserId());
                    }
                    initServerInfo();
                }
            });
            //默认有悬浮窗权限  但是 华为, 小米,oppo等手机会有自己的一套Android6.0以下  会有自己的一套悬浮窗权限管理 也需要做适配
//            Intent intent = new Intent(MainActivity.this, FBService.class);
//            startService(intent);
        }

//        if (isFrist) {
        if (!(ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_PERMISSION_WRITE_EXTERNAL_STORAGE);
        }
//            else {
//                UserManager.ins().cleanCache();
//            }
//        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == OVERLAY_PERMISSION_REQ_CODE) {
            if (Build.VERSION.SDK_INT >= 23) {
                if (!Settings.canDrawOverlays(this)) {
                    Toast.makeText(this, "权限授予失败，无法开启悬浮窗", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this, "权限授予成功！", Toast.LENGTH_SHORT).show();
                    //有悬浮窗权限开启服务绑定 绑定权限
//                    Intent intent = new Intent(SplashActivity.this, FBService.class);
//                    startService(intent);
                }
            }
        }
    }


    boolean isForce;

    private void initServerInfo() {

        String version = String.valueOf(PhoneInfoUtil.getAppVersionName(this));
        String packageName = "com.moli.jasmine";
        String channelId = PhoneInfoUtil.getAppChannel(this);

        API_App.ins().getServerAddress(TAG, version, packageName, channelId, new StringResponseCallback() {

            @Override
            public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                if (ResponseResult.ResultStatus.OK == errCode && !TextUtils.isEmpty(resultValue)) {
                    if (!isInit) {
                        API_Statistics.ins().addctivationData(TAG, SplashActivity.this);
                        PreferenceHelper.ins().storeBooleanShareData(preference_first_key, true);
                        PreferenceHelper.ins().commit();
                    }
                    API_Statistics.ins().addLoginData(TAG, SplashActivity.this, UserManager.ins().getLoginType(), "");

                    API_Discover.ins().getFoundCacheUpdateInfo(TAG, new StringResponseCallback() {
                        @Override
                        public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                            if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                                FoundCacheUpdateResult result = new Gson().fromJson(resultValue, FoundCacheUpdateResult.class);
                                if (null != result && null != result.getRes() && null != result.getRes().getHashmap()) {
                                    if (UserManager.ins().getBannerVersion() < result.getRes().getHashmap().getExploreBanner()) {
                                        UserManager.ins().updateBannerVersion(result.getRes().getHashmap().getExploreBanner());
                                        UserManager.ins().updateBannerUpdateState(false);
                                    }
                                    if (UserManager.ins().getHotSpecialVersion() < result.getRes().getHashmap().getExploreSpecial()) {
                                        UserManager.ins().updateHotSpecialVersion(result.getRes().getHashmap().getExploreSpecial());
                                        UserManager.ins().updateHotSpecialUpdateState(false);
                                    }
                                    if (UserManager.ins().getEveryMusicVersion() < result.getRes().getHashmap().getExploreEveryMusic()) {
                                        UserManager.ins().updateEveryMusicVersion(result.getRes().getHashmap().getExploreEveryMusic());
                                        UserManager.ins().updateEveryMusicUpdateState(false);
                                    }
                                    if (UserManager.ins().getAlbumVersion() < result.getRes().getHashmap().getExploreAlbum()) {
                                        UserManager.ins().updateAlbumVersion(result.getRes().getHashmap().getExploreAlbum());
                                        UserManager.ins().updateAlbumUpdateState(false);
                                    }
                                }
                            }
                            return false;
                        }
                    });
                    final InitResult result = new Gson().fromJson(resultValue, InitResult.class);
                    if (null != result && null != result.getRes() && null != result.getRes().getDataclienturl()) {
                        String httpServerDomain = result.getRes().getDataclienturl().getServerwebUrl();
                        ServerAddressManager.updateDomain(httpServerDomain);
                        if (result.getRes().getDataclienturl().getOperateStat() == InitResult.Res.Data.STATE_NEED_UPDATE || result.getRes().getDataclienturl().getOperateStat() == InitResult.Res.Data.STATE_UPDATE) {
                            mHandler.removeMessages(MESSAGE_WHAT_GOTO_MAINACTIVITY);
                            getSplashAdverData(false);
                            if (InitResult.Res.Data.STATE_UPDATE == result.getRes().getDataclienturl().getOperateStat()) {
                                isForce = true;
                            }
                            UpdateDialog td = new UpdateDialog(SplashActivity.this);
                            td.setCanceledOnTouchOutside(false);
                            td.setCancelable(false);
                            if (!TextUtils.isEmpty(result.getRes().getDataclienturl().getUpdateContent())) {
                                td.setTextDes(result.getRes().getDataclienturl().getUpdateVersion(), result.getRes().getDataclienturl().getUpdateContent());
                            }
                            td.setButtonListener(new UpdateDialog.DialogButtonOnClickListener() {
                                public void onClick(View button, UpdateDialog dialog) {
                                    dialog.dismiss();
                                    if (!TextUtils.isEmpty(result.getRes().getDataclienturl().getUpdateUrl())) {
                                        String downloadUrl = result.getRes().getDataclienturl().getUpdateUrl();
                                        if (!downloadUrl.startsWith("http://") && !downloadUrl.startsWith("https://"))
                                            downloadUrl = "http://" + downloadUrl;
                                        Uri uri = Uri.parse(downloadUrl);
                                        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                                        SplashActivity.this.startActivity(intent);
                                    }

                                    if (isForce) {
                                        SplashActivity.this.finish();
                                    } else {
                                        isPauseForUpdate = true;
                                        onPause();
                                    }
                                }
                            });
                            td.setButtonCloseListener(new UpdateDialog.DialogButtonOnClickListener() {
                                public void onClick(View button, UpdateDialog dialog) {
                                    dialog.dismiss();
                                    if (isForce) {
                                        SplashActivity.this.finish();
                                    } else {
                                        handleIntent();
                                    }
                                }
                            });
                            if (!td.isShowing()) {
                                td.show();
                            }
                        } else {
                            getSplashAdverData(true);
                        }

                    } else {
                        handleIntent();
                    }
                } else {
                    handleIntent();
                }
                return false;
            }
        });
    }

    @Override
    protected void onPause() {
        super.onPause();
    }


    private boolean isPauseForUpdate = false;

    private void getSplashAdverData(final boolean isCanGO) {
        API_Found.ins().getAdvertisementList(TAG, AppKey.AD_TYPE_SPLASH, CacheMode.DEFAULT, new StringResponseCallback() {
            @Override
            public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                    AdvertisementListResult result = new Gson().fromJson(resultValue, AdvertisementListResult.class);

                    if (null != result && null != result.getRes() && null != result.getRes().getArraylist()) {
                        if (result.getRes().getArraylist().size() > 0) {
                            advert = result.getRes().getArraylist().get(0);
                            if (!TextUtils.isEmpty(result.getRes().getArraylist().get(0).getImage())) {
                                BitmapLoader.ins().loadImage(result.getRes().getArraylist().get(0).getImage(), 0, iv_splash, new ImageLoadingListener() {
                                    @Override
                                    public void onLoadingStarted(String s, View view) {

                                    }

                                    @Override
                                    public void onLoadingFailed(String s, View view, FailReason failReason) {
                                        DELAY_TIME = 500;
                                        if (isCanGO) {
                                            handleIntent();
                                        }
                                    }

                                    @Override
                                    public void onLoadingComplete(String s, View view, Bitmap bitmap) {
                                        DELAY_TIME = 3000;
                                        tvSkipAd.setVisibility(View.VISIBLE);
                                        if (isCanGO) {
                                            handleIntent();
                                        }
                                    }

                                    @Override
                                    public void onLoadingCancelled(String s, View view) {

                                    }
                                });
                            }
                        } else {
                            if (isCanGO) {
                                handleIntent();
                            }
                        }
                    } else {
                        if (isCanGO) {
                            handleIntent();
                        }
                    }
                } else {
                    if (isCanGO) {
                        handleIntent();
                    }
                }
                return false;
            }
        });
    }

    public static final int REQUEST_PERMISSION_WRITE_EXTERNAL_STORAGE = 0x01;

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PERMISSION_WRITE_EXTERNAL_STORAGE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                UserManager.ins().cleanCache();
                chearCacheIfTooMore();
            }
        }
    }

    public void chearCacheIfTooMore() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                final double imageSize = FileSizeUtil.getFileOrFilesSize(RT.defaultImage, FileSizeUtil.SIZETYPE_MB);
                final double cacheSize = FileSizeUtil.getFileOrFilesSize(RT.defaultCache, FileSizeUtil.SIZETYPE_MB);
                if ((imageSize + cacheSize) > 500) {
                    UserManager.ins().cleanImageCache();
                }
            }
        }).start();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_splash:
                if (advert != null && !ClickUtil.isFastDoubleClick()) {
                    mHandler.removeMessages(MESSAGE_WHAT_GOTO_MAINACTIVITY);
                    ViewGT.processAdvertisement(this, advert);
                }
                finish();
                break;
            case R.id.tvSkipAd:
                DELAY_TIME = 0;
                mHandler.removeMessages(MESSAGE_WHAT_GOTO_MAINACTIVITY);
                mHandler.sendEmptyMessage(MESSAGE_WHAT_GOTO_MAINACTIVITY);
                break;
        }

    }

    Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MESSAGE_WHAT_GOTO_MAINACTIVITY:
                    UserManager.ins().loadUserInfo(new UserManager.LoadCallBack() {
                        @Override
                        public void onComlpete() {
                            Intent main_intent = null;
                            if (!UserManager.ins().isLogin()) {
                                main_intent = new Intent(SplashActivity.this, PhoneLoginActivity.class);
                                main_intent.putExtra("canBack", true);
                            } else {
                                main_intent = new Intent(SplashActivity.this, MainActivity.class);
                            }
                            main_intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
                            startActivity(main_intent);
                            overridePendingTransition(R.anim.zoom_enter, R.anim.zoom_exit);
                            finish();
                        }
                    });

                    break;
                case MESSAGE_WHAT_GOTO_GUIDEACTIVITY:
//                    Intent guide_intent = new Intent(SplashActivity.this, GuideActivity.class);
//                    guide_intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                    startActivity(guide_intent);
//                    overridePendingTransition(R.anim.zoom_enter, R.anim.zoom_exit);
//                    finish();
                    break;
            }


        }
    };

    private void handleIntent() {
//        if (isFrist) {
//            mHandler.sendEmptyMessageDelayed(MESSAGE_WHAT_GOTO_GUIDEACTIVITY, DELAY_TIME);
//        } else {
        mHandler.sendEmptyMessageDelayed(MESSAGE_WHAT_GOTO_MAINACTIVITY, DELAY_TIME);
//        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isPauseForUpdate) {
            handleIntent();
        }
        if (isPauseForPermission) {
            UserManager.ins().loadUserInfo(new UserManager.LoadCallBack() {
                @Override
                public void onComlpete() {
                    if (UserManager.ins().isLogin()) {
                        UserManager.ins().loginChat(UserManager.ins().getUserId());
                    }
                    initServerInfo();
                }
            });
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkHttpUtils.getInstance().cancelTag(TAG);
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
    }

}
